/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.agenda;

import com.je.bpm.core.model.FlowNode;
import com.je.bpm.engine.impl.delegate.InactiveActivityBehavior;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.util.ProcessDefinitionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.je.bpm.core.model.process.Process;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Operation that usually gets scheduled as last operation of handling a {@link com.je.bpm.engine.impl.interceptor.Command}.
 *
 * Executes 'background' behaviours of executions that currently are in an activity that implements
 * the {@link InactiveActivityBehavior} interface.
 */
public class ExecuteInactiveBehaviorsOperation extends AbstractOperation {

    private static final Logger logger = LoggerFactory.getLogger(ExecuteInactiveBehaviorsOperation.class);

    protected Collection<ExecutionEntity> involvedExecutions;

    public ExecuteInactiveBehaviorsOperation(CommandContext commandContext) {
        super(commandContext, null);
        this.involvedExecutions = commandContext.getInvolvedExecutions();
    }

    @Override
    public void run() {

        /*
         * Algorithm: for each execution that is involved in this command context,
         *
         * 1) Get its process definition
         * 2) Verify if its process definitions has any InactiveActivityBehavior behaviours.
         * 3) If so, verify if there are any executions inactive in those activities
         * 4) Execute the inactivated behavior
         *
         */

        for (ExecutionEntity executionEntity : involvedExecutions) {

            Process process = ProcessDefinitionUtil.getProcess(executionEntity.getProcessDefinitionId());
            Collection<String> flowNodeIdsWithInactivatedBehavior = new ArrayList<String>();
            for (FlowNode flowNode : process.findFlowElementsOfType(FlowNode.class)) {
                if (flowNode.getBehavior() instanceof InactiveActivityBehavior) {
                    flowNodeIdsWithInactivatedBehavior.add(flowNode.getId());
                }
            }

            if (flowNodeIdsWithInactivatedBehavior.size() > 0) {
                Collection<ExecutionEntity> inactiveExecutions = commandContext.getExecutionEntityManager().
                        findInactiveExecutionsByProcessInstanceId(executionEntity.getProcessInstanceId());
                for (ExecutionEntity inactiveExecution : inactiveExecutions) {
                    if (!inactiveExecution.isActive()
                            && flowNodeIdsWithInactivatedBehavior.contains(inactiveExecution.getActivityId())
                            && !inactiveExecution.isDeleted()) {

                        FlowNode flowNode = (FlowNode) process.getFlowElement(inactiveExecution.getActivityId(), true);
                        InactiveActivityBehavior inactiveActivityBehavior = ((InactiveActivityBehavior) flowNode.getBehavior());
                        logger.debug("Found InactiveActivityBehavior instance of class {} that can be executed on activity '{}'", inactiveActivityBehavior.getClass(), flowNode.getId());
                        inactiveActivityBehavior.executeInactive(inactiveExecution);
                    }
                }
            }

        }
    }

}
